<?php
/**
*=========================
*		    橘子PHP框架   =
*=========================
*      QQ:1691954622     =
*=========================
*/
//引入配置文件
require CORE.'config.php';
//获取控制器和方法
$query = $_GET;$controller = isset($query['c']) ? $query['c'] : C;
$action = isset($query['a']) ? $query['a'] : A;
// 实例化用户请求类并调用方法
if (file_exists(APP.$controller.'.php')) {
  require APP.$controller.'.php';
if (class_exists($controller)) {
 if (method_exists($controller, $action)) {
       unset($_GET['c']);
       unset($_GET['a']);       
       (new $controller())->$action();
   } else {
       $e = '控制器' . $controller . '中不存在方法' . $action;
       require CORE.'error.html';
   }
} else { 
   $e = '不存在控制器' . $controller;
   require CORE.'error.html';
}
}else{
  $e = '不存在控制器' . $controller;
  require CORE.'error.html';
}
/**
* ----污橘
*/
class wuju
{
	/**
	** @param  $conn [数据库]
     * [assign description]
     * @param  [type] $name  [变量名]
     * @param  [type] $value [变量值]
     */
	protected $link;
	protected $assign = [];
	//SQL操作

	public function __construct()
	{
		if (!$this->link = mysqli_connect(HOST,USER,PASS,DBNAME)) {
			$e = '连接失败：'.mysqli_connect_error();
			require CORE.'error.html';
		}
	}
	private function db_connect(){
    $this->link=mysqli_connect($this->host.':'.$this->port,$this->user,$this->pass);
    if(!$this->link){
      echo "数据库连接失败<br>";
      echo "错误编码".mysqli_errno($this->link)."<br>";
      echo "错误信息".mysqli_error($this->link)."<br>";
      exit;
    }
   }
   //设置字符集
    private function db_charset(){
     mysqli_query($this->link,"set names {$this->charset}");
    }
    //选择数据库
   private function db_usedb(){
     mysqli_query($this->link,"use {$this->db}");
   }
   //私有的克隆
   private function __clone(){
     die('clone is not allowed');
   }
   //公用的静态方法
   public static function getIntance(){
     if(self::$dbcon==false){
      self::$dbcon=new self;
     }
     return self::$dbcon;
   }
   //执行sql语句的方法
    public function query($sql){
     $res=mysqli_query($this->link,$sql);
     if(!$res){
      echo "sql语句执行失败<br>";
      echo "错误编码是".mysqli_errno($this->link)."<br>";
      echo "错误信息是".mysqli_error($this->link)."<br>";
     }
     return $res;
   }
   //打印数据
    public function p($arr){
      echo "<pre>";
      print_r($arr);
      echo "</pre>";
    }
    public function v($arr){
      echo "<pre>";
      var_dump($arr);
      echo "</pre>";
    }
    //获得最后一条记录id
    public function getInsertid(){
     return mysqli_insert_id($this->link);
    }
   /**
    * 查询某个字段
    * @param
    * @return string or int
    */
    public function getOne($sql){
     $query=$this->query($sql);
      return mysqli_free_result($query);
    }
    //获取一行记录,return array 一维数组
    public function getRow($sql,$type="assoc"){
     $query=$this->query($sql);
     if(!in_array($type,array("assoc",'array',"row"))){
       die("mysqli_query error");
     }
     $funcname="mysqli_fetch_".$type;
     return $funcname($query);
    }
    //获取一条记录,前置条件通过资源获取一条记录
    public function getFormSource($query,$type="assoc"){
    if(!in_array($type,array("assoc","array","row")))
    {
      die("mysqli_query error");
    }
    $funcname="mysqli_fetch_".$type;
    return $funcname($query);
    }
    //获取多条数据，二维数组
    public function getAll($sql){
     $query=$this->query($sql);
     $list=array();
     while ($r=$this->getFormSource($query)) {
      $list[]=$r;
     }
     return $list;
    }
     /**
     * 定义添加数据的方法
     * @param string $table 表名
     * @param string orarray $data [数据]
     * @return int 最新添加的id
     */
     public function insert($table,$data){
     //遍历数组，得到每一个字段和字段的值
     $key_str='';
     $v_str='';
     foreach($data as $key=>$v){
      if(empty($v)){
       die("error");
     }
        //$key的值是每一个字段s一个字段所对应的值
        $key_str.=$key.',';
        $v_str.="'$v',";
     }
     $key_str=trim($key_str,',');
     $v_str=trim($v_str,',');
     //判断数据是否为空
     $sql="insert into $table ($key_str) values ($v_str)";
     $this->query($sql);
    //返回上一次增加操做产生ID值
     return $this->getInsertid();
   }
   /*
    * 删除一条数据方法
    * @param1 $table, $where=array('id'=>'1') 表名 条件
    * @return 受影响的行数
    */
    public function deleteOne($table, $where){
      if(is_array($where)){
        foreach ($where as $key => $val) {
          $condition = $key.'='.$val;
        }
      } else {
        $condition = $where;
      }
      $sql = "delete from $table where $condition";
      $this->query($sql);
      //返回受影响的行数
      return mysqli_affected_rows($this->link);
    }
    /*
    * 删除多条数据方法
    * @param1 $table, $where 表名 条件
    * @return 受影响的行数
    */
    public function deleteAll($table, $where){
      if(is_array($where)){
        foreach ($where as $key => $val) {
          if(is_array($val)){
            $condition = $key.' in ('.implode(',', $val) .')';
          } else {
            $condition = $key. '=' .$val;
          }
        }
      } else {
        $condition = $where;
      }
      $sql = "delete from $table where $condition";
      $this->query($sql);
      //返回受影响的行数
      return mysqli_affected_rows($this->link);
    }
   /**
    * [修改操作description]
    * @param [type] $table [表名]
    * @param [type] $data [数据]
    * @param [type] $where [条件]
    * @return [type]
    */
   public function update($table,$data,$where){
     //遍历数组，得到每一个字段和字段的值
     $str='';
    foreach($data as $key=>$v){
     $str.="$key='$v',";
    }
    $str=rtrim($str,',');
    //修改SQL语句
    $sql="update $table set $str where $where";
    $this->query($sql);
    //返回受影响的行数
    return mysqli_affected_rows($this->link);
   }
	//视图
	public  function assign($name,$value){
		if (isset($name)) {
			$this->assign[$name] = $value;
		}
       
    }
    /**
     * [display description]
     * @param  [type] $file [文件名]
     */
	public function display($file){
    $controller = isset($query['c']) ? $query['c'] : C;
		$file = APP.'views/'.$controller.'/'.$file.SUffIX;
			if (is_file($file)) {
				extract($this->assign);//将数组打散
        		require $file;
    	}else{
    		$e = '不存在此视图'.$file.SUffIX;
   			require CORE.'error.html';
    	}
	}
	public function ip($type = 0) {
    	$type = $type ? 1 : 0;
    	static $ip = NULL;
    	if ($ip !== NULL) return $ip[$type];
    	if (@$_SERVER['HTTP_X_REAL_IP']) {//nginx 代理模式下，获取客户端真实IP
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    	} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    	} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
        	$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        	$pos = array_search('unknown', $arr);
        	if (false !== $pos) unset($arr[$pos]);
        	$ip = trim($arr[0]);
    	} elseif (isset($_SERVER['REMOTE_ADDR'])) {
       		$ip = $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
    	} else {
        	$ip = $_SERVER['REMOTE_ADDR'];
    	}
    // IP地址合法验证
    	$long = sprintf("%u", ip2long($ip));
    	$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    	return $ip[$type];
	}
}